#include <iostream>

using std::cout;
using std::endl;


class Singleton
{
    //AutoRelease是为解决Singleton的问题而生的
    //只需要作为嵌套类就可以了
    class AutoRelease
    {
    public:
        AutoRelease()
        {   cout << "AutoRelease()" << endl;}

        ~AutoRelease() {
            cout << "~AutoRelease()" << endl;
            if(_pInstance) {
                //Singleton中的静态数据成员_pInstance可以
                //在嵌套类中直接访问
                delete _pInstance;
                _pInstance = nullptr;
            }
        }
    };
public:
    static Singleton * getInstance()
    {
        if(_pInstance == nullptr) {
            _pInstance = new Singleton;
        }
        return _pInstance;
    }

    static void destroy()
    {
        if(_pInstance) {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

    void print() const
    {
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

    void init(int ix, int iy)
    {
        _ix = ix;
        _iy = iy;
    }

private:
    Singleton()
    : _ix(0), _iy(0)
    {   cout << "Singleton()" << endl;  }

    ~Singleton() {   cout << "~Singleton()" << endl;  }

private:
    static Singleton * _pInstance;
    int _ix;
    int _iy;
    static AutoRelease _ar;
};

//静态数据成员要在类之外初始化
Singleton * Singleton::_pInstance = nullptr;
Singleton::AutoRelease Singleton::_ar;


int main()
{
    Singleton * p1 = Singleton::getInstance();
    Singleton * p2 = Singleton::getInstance();
    cout << "p1: " << p1 << endl;
    cout << "p2: " << p2 << endl;
    Singleton::getInstance()->init(10, 11);//实际操作时的用法
    Singleton::getInstance()->print();
    cout << endl;

    return 0;
}

